package easycloud.ecs.agent.batch;

import java.io.IOException;
import java.util.Map;

import javax.inject.Inject;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import easycloud.ecs.agent.Agent;
import easycloud.ecs.agent.service.KnowledgeService;
import easycloud.ecs.common.domain.Item;
import easycloud.ecs.provider.api.ProviderException;
import easycloud.ecs.sync.Knowledge;

@Service
public class SyncSessionJob {
	private static final Log logger = LogFactory.getLog(SyncSessionJob.class);

	@Inject
	private Agent agent;

	@Inject
	private KnowledgeService knowledgeService;

	/**
	 */
	@Scheduled(fixedRate = 10000, initialDelay = 10000)
	public void execute() {
		logger.debug("Execute SyncSessionJob Begin");
		try {
			Knowledge know = knowledgeService.getLocalKnowledge();
			// for (IStorageObjectMetadata metadata :
			// know.getMetadatas().values()) {
			// System.out.println(metadata.getItem().getPath() + " : "
			// + metadata.getItem().getFolder());
			// }
			Map<String, Item> remoteItems = knowledgeService
					.getRemoteMetadata(agent.getProvider());
			// for (Item item : remoteItems.values()) {
			// System.out.println(item.getPath() + " : " + item.getFolder());
			// }
			knowledgeService.merge(know, remoteItems);
			System.out.println(know);
			// for (IStorageObjectMetadata metadata :
			// know.getMetadatas().values()) {
			// System.out.println(metadata.getItem().getPath() + " : "
			// + metadata.getItem().getFolder());
			// }
			knowledgeService.updateServer(know.getLocalItems());

			knowledgeService.updateConflict(know.getConflictItems());

			knowledgeService.updateLocal(know.getRemoteItems());
		} catch (ProviderException | IOException e) {
			e.printStackTrace();
		}
		logger.debug("Execute SyncSessionJob End");
	}

}
